import {Button, Form, message, Modal} from 'antd';
import {WeaSearchGroup, WeaTools, WeaDialog, WeaFormItem} from 'ecCom';
import {WeaSwitch} from 'comsMobx'
import {toJS} from 'mobx';
import {WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
const confirm = Modal.confirm;

//删除操作
const doDelete = (params) => {
  return WeaTools.callApi('/api/doc/operate/delete', 'GET', params);
}

// 工作交流直接搜索
const workPlanExchangeDirectSearch = (store, viewcondition) => {
  if(store === undefined) return;
  if (viewcondition == 6) {
    store.setCurrent(1, () => {
      store.doSearch({
        CompParams: {
          viewcondition: '0'
        }
      });
    });
  } else {
    store.setCurrent(1, () => {
      store.doSearch({
        CompParams: {
          viewcondition: viewcondition || '0'
        }
      });
    });
  }
}

//得到右键菜单
//CompStore指定要使用此方法的组件自己所特有的组件，
//TableMobxStore指定WadTableMobx所有的Store
export function getRightMenu(CompStore, TableMobxStore, bool = true) {
  const {dataKey} = CompStore;
  //无筛选条件时的table的sessionkey
  const tableKey = dataKey !== '0' ? dataKey.split('_')[0] : 'init';
  const selectedRowKeys = TableMobxStore.selectedRowKeys;

  let isDisabled = true;
  let arr = []
  if (bool) {
    arr = [{
      key: 'add',
      icon: <i className='icon-coms-plus'/>,
      content: getLabel(611, '添加'),
      onClick: key => {
        CompStore.openAddDialog();
        //用于新建表格中一行数据的相关方法，若存在，也调用
        if (CompStore.pageName === "planModul") {
          CompStore.doNewData();
          CompStore.setIfHideSomeAboutFieldObj();
        }
      }
    }, {
      key: 'batchDelete',
      icon: <i className='icon-coms-Batch-delete'/>,
      content: getLabel(32136, '批量删除'),
      disabled: selectedRowKeys.length === 0 ? true : false,
      onClick: key => {
        let curSessionKey = CompStore.dataKey,
          tableMobxState = TableMobxStore.state,
          selectedRowKeys = TableMobxStore.selectedRowKeys;
        doMultiDelete(...['MyDoc', TableMobxStore.selectedRowKeys, CompStore]);
      }
    }, {
      key: 'colSet',
      icon: <i className='icon-coms-Custom'/>,
      content: getLabel(382660, '显示定制列'),
      // disabled: selectedRowKeys.length === 0 ? true : false,
      onClick: key => {
        const dataKey = CompStore.dataKey;
        TableMobxStore.setColSetVisible(dataKey, true);
        TableMobxStore.tableColSet(dataKey, true);
      }
    },];
  } else {
    arr = [{
      key: 'batchDelete',
      icon: <i className='icon-coms-Batch-delete'/>,
      content: getLabel(126174, '批量完成'),
      disabled: selectedRowKeys.length === 0 ? true : false,
      onClick: key => {
        let curSessionKey = CompStore.dataKey,
          tableMobxState = TableMobxStore.state,
          selectedRowKeys = TableMobxStore.selectedRowKeys;
        doMultibatchFinish(...['MyDoc', TableMobxStore.selectedRowKeys, CompStore]);
      }
    },{
      key: 'batchExport',
      icon: <i className='icon-coms-download'/>,
      content: getLabel(125595, '全部导出'),
      //disabled: selectedRowKeys.length === 0 ? true : false,
      onClick: key => {
        
        CompStore.exportExcel(CompStore.dataKey);
      }
    }, {
      key: 'colSet',
      icon: <i className='icon-coms-Custom'/>,
      content: getLabel(382660, '显示定制列'),
      // disabled: selectedRowKeys.length === 0 ? true : false,
      onClick: key => {
        const dataKey = CompStore.dataKey;
        TableMobxStore.setColSetVisible(dataKey, true);
        TableMobxStore.tableColSet(dataKey, true);
      }
    },];
  }
  // !bool && (arr.shift())
  return arr
}

//顶部右侧按钮组合，按钮的功能逻辑待做
//store表示将要传给它的store
export function getTopButtons(CompStore, firstButtonName, TableMobxStore) {
  const {dataKey} = CompStore;
  //无筛选条件时的table的sessionkey
  const tableKey = dataKey !== '0' ? dataKey.split('_')[0] : 'init';
  const selectedRowKeys = TableMobxStore.selectedRowKeys;

  const arr = [
    (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ikipqs@openAddDialog`}
      type="primary"
      onClick={() => {
        CompStore.openAddDialog()

        //用于新建表格中一行数据的相关方法，若存在，也调用
        if (CompStore.pageName === "planModul") {
          CompStore.doNewData();
          CompStore.setIfHideSomeAboutFieldObj();
        }

      }}
    >
      {firstButtonName}
    </Button>),

    (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vez5qf@doMultiDelete`}
      type="primary"
      disabled={selectedRowKeys.length === 0 ? true : false}
      onClick={() => {
        doMultiDelete(...['MyDoc', TableMobxStore.selectedRowKeys, CompStore]);
      }}
    >
      {getLabel(32136, '批量删除')}
    </Button>),

  ];
  return arr;
}


//用于获取高级搜索中的表单控件
export function getSearchs(store, onEnterSearch) {
  const FormItem = Form.Item;
  // const conditioninfo = adFormdatas.condition;
  let {form, conditioninfo} = store;
  conditioninfo = toJS(conditioninfo);
  const {isFormInit} = form;
  let group = [];
  // 获取表单的值
  const formParams = form.getFormParams();
  // isFormInit 为true，form已经初始化完成

  if(typeof onEnterSearch !== 'function') {
    onEnterSearch = () => {
      if (store.pageName === 'workPlanExchange') {
        const viewcondition = store.form.getFormParams().timeSag;
        workPlanExchangeDirectSearch(store, viewcondition);
      } else {
        store.doSearch();
      }
      store.setShowSearchAd(false);
    }
  }

  isFormInit && conditioninfo.map((c, _index) => {
    let items = [];
    c.items.map(fields => {
      if(fields.domkey[0] == 'isOvertime'){
        const planstatus = formParams.planstatus || ''
        if(planstatus == '0'){
          items.push({
            com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@xj8msq@${fields.domkey[0]}`}
              label={`${fields.label}`}
              labelCol={{span: `${fields.labelcol}`}}
              wrapperCol={{span: `${fields.fieldcol}`}}>
              {/*根据 WeaSwitch 获取对应的组件*/}
              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@6uz00a@${fields.domkey[0]}`} fieldConfig={fields} form={form} formParams={formParams} onEnterSearch={onEnterSearch}/>
            </WeaFormItem>),
            colSpan: 1
          })
        }
      }else {
        items.push({
          com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@90vblg@${fields.domkey[0]}`}
            label={`${fields.label}`}
            labelCol={{span: `${fields.labelcol}`}}
            wrapperCol={{span: `${fields.fieldcol}`}}>
            {/*根据 WeaSwitch 获取对应的组件*/}
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@e9q0xu@${fields.domkey[0]}`} fieldConfig={fields} form={form} formParams={formParams} onEnterSearch={onEnterSearch}/>
          </WeaFormItem>),
          colSpan: 1
        })
      }
      
    });
    group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@9s1no6@${_index}`} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
  });
  return group;
}

//定义tab中点击高级搜索时的最下面的操作按钮集合
export function getTabButtonsAd(store) {
  return [
    (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@iki0al@setShowSearchAd`}
      type="primary"
      onClick={() => {
        //使得高级搜索在点击搜索按钮2后也能跳转到相应的tab页
        if (store.pageName === 'workPlanExchange') {
          const viewcondition = store.form.getFormParams().timeSag;
          workPlanExchangeDirectSearch(store, viewcondition);
        } else {
          store.doSearch();
        }
        store.setShowSearchAd(false);
      }}
    >
      {getLabel(197, '搜索')}
    </Button>),
    (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@2axizj@resetAdSearchForm`} type="ghost" onClick={() => {
      store.resetAdSearchForm()
    }}>{getLabel(2022, '重置')}</Button>),
    (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@y2x3aw@cancel`} type="ghost" onClick={() => {
      store.setShowSearchAd(false)
    }}>{getLabel(31129, '取消')}</Button>)
  ]
}


//批量删除
export const doMultiDelete = (module, params, store) => {
  let ids;
  if (typeof params === 'string') {
    ids = params.split(",");
  } else {
    ids = params;
  }
  let success = [];
  let error = [];

  confirm({
    title: `${getLabel(131329, '信息确认')}`,
    content: (<span>{getLabel(15097, '确定要删除吗？')}</span>),
    onOk() {
      for (var i = 0; i < ids.length; i++) {
        let rdata = store.interfaceOfDeleteTableData({workid: ids[i], isSys: 0}).then(rdata => {
          if (rdata.status == 1) {
            success.push(rdata);
          } else {
            error.push(rdata);
          }

          if (success.length + error.length == ids.length) {
            if (error.length > 0) {
              for (var j = 0; i < error.length; j++) {
                message.error(getLabel(20462, '删除失败'));
              }
            } else {
              message.success(getLabel(20461, '删除成功'));
              //window.store_e9_element.dispatch(ComsAction.doSearch(module));
              //这个应该要变为mobx的store里的dosearch
              store.doSearch();
            }
          }
        });
      }
    },
    onCancel() {
    }
  })
};

//批量完成
export const doMultibatchFinish = (module, params, store) => {
  let ids = toJS(params).join(',')
  confirm({
    title: getLabel(131329, '信息确认'),
    content: (<span>{getLabel(126220, '确定要完成吗？')}</span>),
    onOk() {
      store.batchFinish(ids)
    },
    onCancel() {
    }
  })
};

//拼接url链接
export const buildUrlStr = (params = {}) => {
  let str = "";
  _.forIn(params, (value, key) => {
      str += `&${key}=${value}`;
  });
  if (str !== "")
      str = str.substring(1);
  return str;
}
